package org.example.crm.auth.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.example.crm.auth.LoginException;
import org.example.crm.auth.entity.Menu;
import org.example.crm.auth.entity.User;
import org.example.crm.auth.service.IMenuService;
import org.example.crm.auth.service.ITokenService;
import org.example.crm.auth.service.IUserService;
import org.example.crm.auth.vo.LoginVO;
import org.example.crm.auth.vo.Token;
import org.example.crm.common.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

import static org.example.crm.common.RedisService.TOKEN_PREFIX;

@Service
public class TokenServiceImpl implements ITokenService {
    @Autowired
    private IUserService userService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private RedisService redisService;

    @Override
    public Token create(LoginVO loginVO) throws LoginException {
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, loginVO.getUsername()));
        if (user == null)
            throw new LoginException("用户不存在");

        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        if (!passwordEncoder.matches(loginVO.getPassword(), user.getPassword())) {
            throw new LoginException("密码不正确");
        }

        List<Menu> menuList = menuService.listByUserId(user.getUserId());
        List<String> apiList = menuList.stream()
                .filter(menu -> StringUtils.hasText(menu.getApiUrl()))
                .map(menu -> menu.getHttpMethod() + "_" + menu.getApiUrl())
                .collect(Collectors.toList());
        // 生成token
        String uuid = UUID.randomUUID().toString();
        Token token = new Token();
        token.setToken(uuid);
        token.setNickName(user.getNickName());
        // 保存到redis
        redisService.set(TOKEN_PREFIX + uuid, apiList.stream().collect(Collectors.joining(",")), Duration.ofMinutes(30));
        return token;
    }

    public boolean logout(String token) {
        return redisService.del(TOKEN_PREFIX + token);
    }

    public static void main(String[] args) {
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        System.out.println("passwordEncoder.encode(\"123\") = " + passwordEncoder.encode("123"));
    }
}
